import org.junit.jupiter.api.Test;

public class _13_罗马数字转数字 {
    @Test
    void test(){
        System.out.println(romanToInt("LVIII"));
    }

    public int romanToInt(String  s) {
        //定义所有可能的数字
        int [] nums={1000,900,500,400,100,90,50,40,10,9,5,4,1};
        String[] num_str={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        //遍历nums，把每一次小于num的数都减掉，然后拼接字符串，直到为零输出罗马数字
        int sum=0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            //CM的情况
            if (chars[i]=='C'){
                if (i< chars.length-1&&chars[i+1]=='M'){
                    sum+=nums[1];
                    i++;
                    continue;
                }

            }
            //CD的情况
            if (chars[i]=='C'){
                if (i< chars.length-1&&chars[i+1]=='D'){
                    sum+=nums[3];
                    i++;
                    continue;
                }
            }
            //XC的情况
            if (chars[i]=='X'){
                if (i< chars.length-1&&chars[i+1]=='C'){
                    sum+=nums[5];
                    i++;
                    continue;
                }
            }
            //XL的情况
            if (chars[i]=='X'){
                if (i< chars.length-1&&chars[i+1]=='L'){
                    sum+=nums[7];
                    i++;
                    continue;
                }
            }
            //XL的情况
            if (chars[i]=='I'){
                if (i< chars.length-1&&chars[i+1]=='X'){
                    sum+=nums[9];
                    i++;
                    continue;
                }
            }            //XL的情况
            if (chars[i]=='I'){
                if (i< chars.length-1&&chars[i+1]=='V'){
                    sum+=nums[11];
                    i++;
                    continue;

                }
            }
            for (int i1 = 0; i1 < num_str.length; i1++) {
                if (num_str[i1].equals(String.valueOf(chars[i]))){
                    sum+=nums[i1];
                    break;
                }
            }
        }
        return sum;
    }
}
